package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"k8s.io/apimachinery/pkg/util/json"
	"shuqi-novel/models/cache"
	"shuqi-novel/models/mysql"
	"shuqi-novel/shuqirpc/internal/svc"
	"shuqi-novel/shuqirpc/shuqirpc"
	"time"
)

type BookListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookListLogic {
	return &BookListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookListLogic) BookList(in *shuqirpc.BookListRequest) (*shuqirpc.BookListResponse, error) {
	// todo: add your logic here and delete this line
	var books []mysql.BookList

	key := fmt.Sprintf("book_add_%s", in) //输入in就是输入所有的请求

	result, _ := cache.RDB.Get(l.ctx, key).Result()

	if result == "" {
		tx := mysql.DB.Debug().Model(&mysql.Book{}).
			Select("books.*,users.name").
			Joins("left join users on books.user_id = users.id").
			Where("user_id = ?", in.UserId)

		if in.Title != "" {
			tx.Where("title like ?", "%"+in.Title+"%")
		}

		tx.Scopes(mysql.Paginate(int(in.Page), int(in.Size))).Find(&books)

		marshal, _ := json.Marshal(books)
		cache.RDB.Set(l.ctx, key, marshal, time.Minute*5)

	} else {
		json.Unmarshal([]byte(result), &books)
	}

	var bookList []*shuqirpc.BookList
	for _, book := range books {
		list := shuqirpc.BookList{
			Title:  book.Title,
			Image:  book.Image,
			UserId: book.UserId,
			Info:   book.Info,
		}
		bookList = append(bookList, &list)
	}

	return &shuqirpc.BookListResponse{
		List: bookList,
	}, nil
}
